#ifndef PRESENTATION_VIEWMODELS_VEHICLE_VIEW_MODEL_H
#define PRESENTATION_VIEWMODELS_VEHICLE_VIEW_MODEL_H

#include "base_view_model.h"
#include "application/vehicle/vehicle_service.h"
#include "kernel/dtos/agv_dto.h"
#include <QAbstractListModel>
#include <QHash>
#include <QString>
#include <QStringList>
#include <QVariantList>
#include <QTimer>
#include <memory>

namespace presentation {
namespace viewmodels {

// AGV列表项（用于QML绑定）
class AgvListItem {
    Q_GADGET
    Q_PROPERTY(int agvNumber MEMBER m_agvNumber)
    Q_PROPERTY(QString name MEMBER m_name)
    Q_PROPERTY(QString ipAddress MEMBER m_ipAddress)
    Q_PROPERTY(QString location MEMBER m_location)
    Q_PROPERTY(QString currentJob MEMBER m_currentJob)
    Q_PROPERTY(int batteryLevel MEMBER m_batteryLevel)
    Q_PROPERTY(bool isOnline MEMBER m_isOnline)
    Q_PROPERTY(bool isCharging MEMBER m_isCharging)
    Q_PROPERTY(bool isControlled MEMBER m_isControlled)

public:
    int m_agvNumber{0};
    QString m_name;
    QString m_ipAddress;
    QString m_location;
    QString m_currentJob;
    int m_batteryLevel{100};
    bool m_isOnline{false};
    bool m_isCharging{false};
    bool m_isControlled{false};
};

// AGV列表模型
class AgvListModel : public QAbstractListModel {
    Q_OBJECT
public:
    enum class DisplayState {
        Offline = 0,
        EstopOrLocked,
        Blocked,
        Charging,
        Executing,
        Idle
    };
    Q_ENUM(DisplayState)

    enum AgvRoles {
        AgvNumberRole = Qt::UserRole + 1,
        NameRole,
        IpAddressRole,
        TypeRole,
        LocationRole,
        CurrentStationRole,
        LastStationRole,
        TargetStationRole,
        CurrentMapRole,
        CurrentJobRole,
        XRole,
        YRole,
        AngleRole,
        ConfidenceRole,
        BatteryLevelRole,
        IsOnlineRole,
        IsChargingRole,
        IsLockedRole,
        IsBlockedRole,
        ModeRole,
        TaskStatusRole,
        TaskTypeRole,
        IsControlledRole,
        ErrorMessageRole,
        UploadTimeRole,
        FinishedPathRole,
        UnfinishedPathRole,
        PathLengthRole,
        TaskChainIdRole,
        IsBusyRole,
        DisplayStateRole,
        StatusTagsRole
    };
    Q_ENUM(AgvRoles)

    explicit AgvListModel(QObject* parent = nullptr);
    ~AgvListModel() override = default;

    // QAbstractListModel interface
    int rowCount(const QModelIndex& parent = QModelIndex()) const override;
    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
    QHash<int, QByteArray> roleNames() const override;

    // 获取指定行的完整AGV数据（用于详情页）
    Q_INVOKABLE QVariantMap getAgvData(int row) const;
    Q_INVOKABLE QVariantMap getAgvDataByNumber(int agvNumber) const;
    Q_INVOKABLE int indexOfAgv(int agvNumber) const;

    // Data update methods
    void updateData(const std::vector<kernel::dtos::AgvInfoDTO>& agvList);
    void updateAgv(int agvNumber, const kernel::dtos::AgvInfoDTO& agv);

private:
    std::vector<kernel::dtos::AgvInfoDTO> m_agvList;
};

// 车辆管理ViewModel
class VehicleViewModel : public BaseViewModel {
    Q_OBJECT
    Q_PROPERTY(AgvListModel* agvListModel READ agvListModel CONSTANT)
    Q_PROPERTY(int totalAgvCount READ totalAgvCount NOTIFY totalAgvCountChanged)
    Q_PROPERTY(int onlineAgvCount READ onlineAgvCount NOTIFY onlineAgvCountChanged)
    Q_PROPERTY(int idleAgvCount READ idleAgvCount NOTIFY idleAgvCountChanged)
    Q_PROPERTY(int targetHistoryRevision READ targetHistoryRevision NOTIFY targetHistoryRevisionChanged)

public:
    // Default constructor for QML
    explicit VehicleViewModel(QObject* parent = nullptr);
    // Constructor with service injection
    explicit VehicleViewModel(
        application::vehicle::VehicleService* vehicleService,
        QObject* parent = nullptr);
    ~VehicleViewModel() override = default;

    // Override BaseViewModel methods
    void initialize() override;
    void cleanup() override;

    // 属性访问器
    AgvListModel* agvListModel() { return m_agvListModel.get(); }
    int totalAgvCount() const { return m_totalAgvCount; }
    int onlineAgvCount() const { return m_onlineAgvCount; }
    int idleAgvCount() const { return m_idleAgvCount; }
    int targetHistoryRevision() const { return m_targetHistoryRevision; }

    // QML调用的方法
    Q_INVOKABLE void refreshAgvList();
    Q_INVOKABLE void startCharging(int agvNumber);
    Q_INVOKABLE void stopCharging(int agvNumber);
    Q_INVOKABLE void cancelTask(int agvNumber);
    Q_INVOKABLE void controlJack(int agvNumber, bool raise);
    Q_INVOKABLE void pauseTask(int agvNumber);
    Q_INVOKABLE void resumeTask(int agvNumber);
    Q_INVOKABLE void goToStation(int agvNumber, const QString& station);
    Q_INVOKABLE QVariantList getRecentTargetStations(int agvNumber) const;

    // 仿真车辆管理方法
    Q_INVOKABLE void createSimulationVehicle(const QVariantMap& data);
    Q_INVOKABLE void updateSimulationVehicle(const QVariantMap& data);
    Q_INVOKABLE void deleteSimulationVehicle(int agvNumber);

signals:
    void totalAgvCountChanged();
    void onlineAgvCountChanged();
    void idleAgvCountChanged();
    void agvDataUpdated(int agvNumber);
    void targetHistoryRevisionChanged();

private slots:
    void onRefreshTimer();
    void onVehicleStatusChanged(int agvNumber);
    void onVehicleRegistered(int agvNumber);
    void onVehicleUnregistered(int agvNumber);
    void onVehicleIdle();

private:
    application::vehicle::VehicleService* m_vehicleService;
    std::unique_ptr<AgvListModel> m_agvListModel;
    std::unique_ptr<QTimer> m_refreshTimer;

    int m_totalAgvCount{0};
    int m_onlineAgvCount{0};
    int m_idleAgvCount{0};
    QHash<int, QStringList> m_recentTargetStations;
    int m_targetHistoryRevision{0};

    void updateStatistics();
    void cacheTargetStation(int agvNumber, const QString& station);
};

} // namespace viewmodels
} // namespace presentation

Q_DECLARE_METATYPE(presentation::viewmodels::AgvListItem)

#endif // PRESENTATION_VIEWMODELS_VEHICLE_VIEW_MODEL_H
